package com.maolong.spring.beans.factory.support;

import com.maolong.spring.beans.factory.BeanFactory;
import com.maolong.spring.beans.factory.config.BeanDefinition;
import com.maolong.spring.beans.factory.config.BeanPostProcessor;
import com.maolong.spring.beans.factory.config.ConfigurableBeanFactory;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {

    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    @Override
    public Object getBean(String name) {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name,Object... args) {
        return doGetBean(name,args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) {
        return (T) getBean(name);
    }

    private Object doGetBean(String name, Object[] args) {
        Object singleton = getSingleton(name);
        if (singleton != null){
            return singleton;
        }
        BeanDefinition beanDefinition = getBeanDefinition(name);
        return creatBean(name,beanDefinition,args);
    }

    /**
     * 获取bean定义
     * @param name
     * @return
     */
    protected abstract BeanDefinition getBeanDefinition(String name);

    protected abstract Object creatBean(String beanName, BeanDefinition beanDefinition,Object... args);

    @Override
     public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public List< BeanPostProcessor> getBeanPostProcessors(){
         return this.beanPostProcessors;
    }
}
